package mi.payment.ui.query;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import mi.payment.R;
import mi.payment.adapter.TransactionQueryAdapter;
import mi.payment.db.dao.PayDetail;
import mi.payment.interfaces.DefaultTextWatcher;
import mi.payment.ui.base.ParentActivity;
import mi.payment.utils.CollectionUtil;
import mi.payment.utils.OrderJudgmentUtil;
import mi.payment.utils.ScreenUtil;

/** 按订单号或凭证号查询交易记录 */
public class TransactionSearchActivity extends ParentActivity {

    private EditText edtSearch;
    private ListView listView;
    private View noResult;

    private TransactionQueryAdapter adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_trans_search);
        initView();
    }

    private void initView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(getResources().getColor(R.color.colorBar));
        }
        findViewById(R.id.ic_back).setOnClickListener(this);
        final TextView tvSearch = (TextView) findViewById(R.id.tv_search);
        tvSearch.setOnClickListener(this);
        adapter = new TransactionQueryAdapter(this);
        listView = (ListView) findViewById(R.id.list_view);
        listView.setHeaderDividersEnabled(false);
        View view = new View(this);
        ListView.LayoutParams vParams = new ListView.LayoutParams(ListView.LayoutParams.MATCH_PARENT, ScreenUtil.dp2px(10));
        view.setLayoutParams(vParams);
        listView.addHeaderView(view);
        listView.setAdapter(adapter);
        listView.setOnScrollListener(new OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == SCROLL_STATE_TOUCH_SCROLL) {
                    hideSoftKeyboard();
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(parent.getContext(), TransactionDetailActivity.class);
                //因为存在head view所以当点击item时候，位置会发生一定的偏移导致点击的是前一个item，所以使用parent.getAdapter()而不是adapter
                PayDetail payDetail = (PayDetail) parent.getAdapter().getItem(position);
                intent.putExtra(TransactionDetailActivity.TRANSACTION_DETAIL, payDetail);
                startActivity(intent);
            }
        });
        noResult = findViewById(R.id.tv_no_result);
        edtSearch = (EditText) findViewById(R.id.edt_search);
        edtSearch.addTextChangedListener(new DefaultTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 0) {
                    adapter.clearData();
                }
            }
        });
        edtSearch.setOnEditorActionListener(new OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH
                        || actionId == EditorInfo.IME_ACTION_DONE
                        || actionId == EditorInfo.IME_ACTION_GO) {
                    handleSearch();
                    return true;
                }
                return false;
            }
        });
    }

    private void handleSearch() {
        String keyword = edtSearch.getText().toString();
        if (TextUtils.isEmpty(keyword)) {
            return;
        }
        List<PayDetail> list = mPayDetailModel.queryTransRecord(keyword);
        Collections.sort(list, new Comparator<PayDetail>() {
            @Override
            public int compare(PayDetail lhs, PayDetail rhs) {
                return compareInner(lhs, rhs);
            }
        });
        adapter.setData(list);
        if (CollectionUtil.isEmpty(adapter.getData())) {
            listView.setVisibility(View.GONE);
            noResult.setVisibility(View.VISIBLE);
        } else {
            listView.setVisibility(View.VISIBLE);
            noResult.setVisibility(View.GONE);
        }
        hideSoftKeyboard();
    }

    private int compareInner(PayDetail lhs, PayDetail rhs) {
        boolean lUnknown = OrderJudgmentUtil.isQRUnknownOrder(lhs);
        boolean rUnknown = OrderJudgmentUtil.isQRUnknownOrder(rhs);
        if (lUnknown && !rUnknown) {
            return -1;
        } else if (!lUnknown && rUnknown) {
            return 1;
        }
        return 0;
    }

    @Override
    protected void onResume() {
        super.onResume();
        handleSearch();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ic_back:
                finish();
                break;
            case R.id.tv_search:
                handleSearch();
                break;
        }
    }

    private void hideSoftKeyboard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        if (imm.isActive(edtSearch)) {
            imm.hideSoftInputFromWindow(edtSearch.getWindowToken(), 0);
        }
    }
}
